{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 文件夹排序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from collections import defaultdict\n",
    "import stat\n",
    "\n",
    "# TODO: 未能实现修改本地文件夹的物理排序\n",
    "\n",
    "\n",
    "def get_size(start_path=\".\"):\n",
    "    \"\"\"\n",
    "    递归获取文件夹及其子文件夹和文件的大小（以MB为单位）\n",
    "    \"\"\"\n",
    "    total_size_bytes = 0\n",
    "    for dirpath, dirnames, filenames in os.walk(start_path):\n",
    "        for f in filenames:\n",
    "            fp = os.path.join(dirpath, f)\n",
    "            # 跳过如果它是符号链接\n",
    "            if not os.path.islink(fp):\n",
    "                total_size_bytes += os.path.getsize(fp)\n",
    "                # 将字节转换为MB\n",
    "    total_size_mb = total_size_bytes / (1024 * 1024)\n",
    "    return total_size_mb\n",
    "\n",
    "\n",
    "def list_files_and_folders(start_path=\".\"):\n",
    "    \"\"\"\n",
    "    列出文件夹及其子文件夹和文件的大小，并返回字典（以MB为单位）\n",
    "    \"\"\"\n",
    "    sizes = defaultdict(float)\n",
    "\n",
    "    for dirpath, dirnames, filenames in os.walk(start_path):\n",
    "        # 排除隐藏的子文件夹\n",
    "        dirnames[:] = [\n",
    "            d\n",
    "            for d in dirnames\n",
    "            if not os.stat(os.path.join(dirpath, d)).st_file_attributes\n",
    "            & stat.FILE_ATTRIBUTE_HIDDEN\n",
    "        ]\n",
    "\n",
    "        for f in filenames:\n",
    "            fp = os.path.join(dirpath, f)\n",
    "            # 跳过如果它是符号链接或隐藏文件\n",
    "            if (\n",
    "                not os.path.islink(fp)\n",
    "                and not os.stat(fp).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN\n",
    "            ):\n",
    "                sizes[fp] = os.path.getsize(fp) / (1024 * 1024)  # 直接转换为MB\n",
    "\n",
    "        for d in dirnames:\n",
    "            dp = os.path.join(dirpath, d)\n",
    "            # 计算子文件夹的大小（以MB为单位），并将其添加到sizes字典中\n",
    "            sizes[dp] = get_size(dp)\n",
    "\n",
    "    return sizes\n",
    "\n",
    "\n",
    "def rank_sizes(sizes):\n",
    "    \"\"\"\n",
    "    根据大小对文件/文件夹进行排名\n",
    "    \"\"\"\n",
    "    return sorted(sizes.items(), key=lambda x: x[1], reverse=True)\n",
    "\n",
    "\n",
    "def print_ranked_sizes(ranked_sizes, output_file=\"ranked_sizes.txt\"):\n",
    "    \"\"\"\n",
    "    打印排名后的文件/文件夹大小（以MB为单位）并保存到文件\n",
    "    \"\"\"\n",
    "    with open(output_file, \"w\", encoding=\"utf-8\") as f:\n",
    "        for rank, (path, size) in enumerate(ranked_sizes, start=1):\n",
    "            # 打印到控制台\n",
    "            print(f\"Rank {rank}: {path} - {size:.2f} MB\")\n",
    "            # 写入到文件\n",
    "            f.write(f\"Rank {rank}: {path} - {size:.2f} MB\\n\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    start_path = r\"\"\n",
    "    sizes = list_files_and_folders(start_path)\n",
    "    ranked_sizes = rank_sizes(sizes)\n",
    "    print_ranked_sizes(ranked_sizes, output_file=\"ranked_sizes.txt\")\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
